package com.css.fxfzysx.modules.cztDataMange.service.impl;

import cn.hutool.core.io.FileUtil;
import com.css.fxfzysx.base.attachment.entity.AttachmentInfoEntity;
import com.css.fxfzysx.base.attachment.service.AttachmentInfoService;
import com.css.fxfzysx.base.response.RestResponse;
import com.css.fxfzysx.constants.YNEnum;
import com.css.fxfzysx.modules.cztDataMange.entity.RdInformationEntity;
import com.css.fxfzysx.modules.cztDataMange.exception.ShpFieldException;
import com.css.fxfzysx.modules.cztDataMange.repository.DomeFacilitiesRepository;
import com.css.fxfzysx.modules.cztDataMange.result.ParsingResult;
import com.css.fxfzysx.modules.cztDataMange.service.DomeFacilitiesService;
import com.css.fxfzysx.modules.cztDataMange.utils.GenerationNumberUtil;
import com.css.fxfzysx.modules.cztDataMange.vo.CztMajorProjectsVo;
import com.css.fxfzysx.modules.lifeline.entity.newEntity.SmxVersionEntity;
import com.css.fxfzysx.modules.lifeline.param.RegionParam;
import com.css.fxfzysx.modules.lifeline.repository.LifelineEngineeringRepository;
import com.css.fxfzysx.modules.lifeline.utils.VersionCodeUtils;
import com.css.fxfzysx.modules.vaomeFacilities.entity.CztMajorProjectsEntity;
import com.css.fxfzysx.modules.vaomeFacilities.utils.PinyinAPI;
import com.css.fxfzysx.util.*;
import com.css.fxfzysx.util.hypergraph.service.HypergraphService;
import com.css.fxfzysx.web.PlatformSessionContext;
import com.css.fxfzysx.zcpt.sys.entity.SUser;
import com.css.fxfzysx.zcpt.sys.service.SUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.*;

@Service
@Slf4j
public class DomeFacilitiesServiceImpl implements DomeFacilitiesService {

    @Autowired
    private DomeFacilitiesRepository domeFacilitiesRepository;

    @Autowired
    private AttachmentInfoService attachmentInfoService;

    @Value("${image.localDir}")
    private String localDir;

    @Autowired
    private SUserService sUserService;

    @Autowired
    private GenerationNumberUtil generationNumberUtil;

    @Autowired
    private SUserService userService;

    @Autowired
    private LifelineEngineeringRepository lifelineEngineeringRepository;

    @Autowired
    private VersionCodeUtils versionCodeUtils;

    @Autowired
    private HypergraphService hypergraphService;


    @Override
    public RestResponse parseShp(RegionParam param) {
        this.uniformFileName(param.getFileIds());
        String versionId = "";
        ParsingResult shpData = getShpData(param.getFileIds());
        //保存版本信息
        if (param.getCover() == 1) {
            versionId = updateVersionInfo(param.getId());
            //删除历史的数据
            lifelineEngineeringRepository.deleteOldVersionData(versionId, 17, param.getBridgeType());
        } else {
            AttachmentInfoEntity attach = attachmentInfoService.getAttach(param.getFileIds().split(",")[0]);
            String name = attach.getAttachName().split("\\.")[0];
            versionId = saveVersionInfo(param.getProvince(), param.getCity(), param.getCounty(), 17, name);
        }
        //是否成功
        if (!shpData.getMessage().equals("ok")) {
            return RestResponse.fail(shpData.getMessage());
        }
        hypergraphService.getWorkspaceReload("czt_reservior");
        return this.saveRdInformation(shpData, param, versionId);
    }

    private RestResponse saveRdInformation(ParsingResult shpData, RegionParam param, String versionId) {
        try {
            List<RdInformationEntity> list = getRdInformationList(shpData.getShpList(), param, versionId);
            if (list == null) {
                return RestResponse.fail("字段数量不符合要求");
            }
            for (RdInformationEntity rdInformationEntity : list) {
                domeFacilitiesRepository.saveRdInformation(rdInformationEntity);
            }
            return RestResponse.succeed("导入成功!");
        } catch (Exception e1) {
            log.error(e1.getMessage(), e1);
            return RestResponse.fail("导入失败!");
        }
    }

    private List<RdInformationEntity> getRdInformationList(List<List<Object>> shpList, RegionParam param, String versionId) throws ShpFieldException {
        ArrayList<RdInformationEntity> arrayList = new ArrayList<>();
        for (int i = 0; i < shpList.size(); i++) {
            List<Object> list = shpList.get(i);
            if (list.size() < 16) {
                return null;
            }
            RdInformationEntity entity = new RdInformationEntity();
            entity.setCreateUser(PlatformSessionContext.getUserID());
            entity.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
            entity.setDelFlag(YNEnum.N.toString());
            entity.setUploadTime(new Date());
            entity.setCrId(UUIDGenerator.getUUID());
            entity.setGeom(list.get(0).toString());
            entity.setCrName(ShpAnalyticUtil.getStringVal(list.get(1).toString(), "水坝名称", true));
            entity.setLocation(ShpAnalyticUtil.getStringVal(list.get(2).toString(), "水坝地点", false));
            entity.setLongitude(ShpAnalyticUtil.getStringVal(list.get(3).toString(), "经度", true));
            entity.setLatitude(ShpAnalyticUtil.getStringVal(list.get(4).toString(), "纬度", true));
            entity.setCapacity(ShpAnalyticUtil.getDoubleVal(list.get(5).toString(), "库容（立方米）", true));
            entity.setYear(ShpAnalyticUtil.getStringVal(list.get(6).toString(), "建造年代", true));
            entity.setDamLength(ShpAnalyticUtil.getDoubleVal(list.get(7).toString(), "坝长（米）", true));
            entity.setDamHeight(ShpAnalyticUtil.getDoubleVal(list.get(8).toString(), "坝高（米）", true));
            entity.setTopWidth(ShpAnalyticUtil.getDoubleVal(list.get(9).toString(), "顶宽（米）", true));
            entity.setStructureType(ShpAnalyticUtil.getStringVal(list.get(10).toString(), "结构类型", true));
            entity.setType(ShpAnalyticUtil.getStringVal(list.get(11).toString(), "水坝类型", true));
            entity.setIntensity(ShpAnalyticUtil.getStringVal(list.get(12).toString(), "设防烈度", true));
            entity.setSite(ShpAnalyticUtil.getStringVal(list.get(13).toString(), "位  置", true));
            entity.setSpace(ShpAnalyticUtil.getStringVal(list.get(14).toString(), "场  地", true));
            entity.setFilling(ShpAnalyticUtil.getStringVal(list.get(15).toString(), "填料", true));
            entity.setDamFoundation(ShpAnalyticUtil.getStringVal(list.get(16).toString(), "坝基", true));
            entity.setMaintenanceStatus(ShpAnalyticUtil.getStringVal(list.get(17).toString(), "维护现状", true));
            if (list.size() > 18 && PlatformObjectUtils.isNotEmpty(list.get(18))) {
                entity.setExtends1(list.get(18).toString());
            }
            if (list.size() > 19 && PlatformObjectUtils.isNotEmpty(list.get(19))) {
                entity.setExtends2(list.get(19).toString());
            }
            if (list.size() > 20 && PlatformObjectUtils.isNotEmpty(list.get(20))) {
                entity.setExtends3(list.get(20).toString());
            }
            if (list.size() > 21 && PlatformObjectUtils.isNotEmpty(list.get(21))) {
                entity.setExtends4(list.get(21).toString());
            }
            if (list.size() > 22 && PlatformObjectUtils.isNotEmpty(list.get(22))) {
                entity.setExtends5(list.get(22).toString());
            }
            if (list.size() > 23 && PlatformObjectUtils.isNotEmpty(list.get(23))) {
                entity.setExtends6(list.get(23).toString());
            }
            if (list.size() > 24 && PlatformObjectUtils.isNotEmpty(list.get(24))) {
                entity.setExtends7(list.get(24).toString());
            }
            if (list.size() > 25 && PlatformObjectUtils.isNotEmpty(list.get(25))) {
                entity.setExtends8(list.get(25).toString());
            }
            if (list.size() > 26 && PlatformObjectUtils.isNotEmpty(list.get(26))) {
                entity.setExtends9(list.get(26).toString());
            }
            if (list.size() > 27 && PlatformObjectUtils.isNotEmpty(list.get(27))) {
                entity.setExtends10(list.get(27).toString());
            }
            entity.setCreateUser(PlatformSessionContext.getUserID());
            entity.setCreateUserName(getUserName().getUserName());
            entity.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
            entity.setDelFlag(YNEnum.N.toString());
            entity.setCrId(UUIDGenerator.getUUID());
            entity.setVersionId(versionId);
            arrayList.add(entity);
        }
        return arrayList;
    }

    /**
     * 统一文件名
     *
     * @param fileIds
     */
    public void uniformFileName(String fileIds) {
        String[] idList = fileIds.split(",");
        AttachmentInfoEntity attachRoot = attachmentInfoService.getAttach(idList[0]);
        String attachRootPath = attachRoot.getAttachPath();
        String filePathCurrTime = getFilePathCurrTime(attachRootPath);
        for (int i = 1; i < idList.length; i++) {
            AttachmentInfoEntity attach = attachmentInfoService.getAttach(idList[i]);
            if (getFilePathCurrTime(attach.getAttachPath()).equals(filePathCurrTime)) {
                continue;
            }
            String attachPath = attach.getAttachPath();
            String fileDiskPath = localDir + attachPath;
            FileUtil.rename(new File(fileDiskPath), getNonSuffixFileName(attach.getAttachName()) + "_" + filePathCurrTime + "." + FileUtil.getSuffix(attach.getAttachName()), true);
            String[] s = attachPath.split("_");
            attach.setAttachPath(s[0] + "_" + filePathCurrTime + "." + FileUtil.getSuffix(attach.getAttachName()));
            attachmentInfoService.update(attach);
        }
    }

    private String getNonSuffixFileName(String fileName) {
        return fileName.replaceAll("." + FileUtil.getSuffix(fileName), "");
    }

    private String getFilePathCurrTime(String filePath) {
        return filePath.split("_")[1].replaceAll("." + FileUtil.getSuffix(filePath.split("_")[1]), "");
    }

    public ParsingResult getShpData(String fileIds) {
        //.prj结尾用来校验是否为2000坐标系
        String prj = "";
        //.cpg文件用来获得编码格式,例如utf-8
        String cpg = "";
        //.shp文件用来获得数据
        String shp = "";
        //根据id获取真实地址
        String[] split = fileIds.split(",");
        for (String id : split) {
            //根据id和文件名获取真实的放在磁盘上的文件
            AttachmentInfoEntity attachmentInfoEntity = attachmentInfoService.getAttach(id);
            String attachPath = attachmentInfoEntity.getAttachPath();
            String substring = attachPath.substring(attachPath.length() - 4);
            if (substring.equals(".prj")) {
                prj = localDir + File.separator + attachPath;
            } else if (substring.equals(".cpg")) {
                cpg = localDir + File.separator + attachPath;
            } else if (substring.equals(".shp")) {
                shp = localDir + File.separator + attachPath;
            }
        }
        return ShpAnalyticUtil.analytic(prj, cpg, shp);
    }

    @Override
    public RestResponse importMajorProjects(MultipartFile file, String province, String city, String county, String id, Integer cover, String fileIds) {
        try {
            String fileName = FileUtil.getPrefix(file.getOriginalFilename());
            String versionId = "";
            //保存版本信息
            if (cover == 1) {
                versionId = updateVersionInfo(id);
                //删除历史的数据
                lifelineEngineeringRepository.deleteOldVersionData(versionId, 16, null);
            } else {
                versionId = saveVersionInfo(province, city, county, 16, fileName);
            }
            String user = sUserService.getSUser(PlatformSessionContext.getUserID());
            SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
            String title = "序号\n" +
                    "（必填）,地震名称\n" +
                    "（必填）,发生日期\n" +
                    "（必填）,发生时间\n" +
                    "（必填）,震级\n" +
                    "（必填）,重大工程类别\n" +
                    "（必填）,震中经度\n" +
                    "（必填）,震中纬度\n" +
                    "（必填）,设防情况\n" +
                    "（必填）,年代\n" +
                    "（必填）,6度破坏状态,7度破坏状态,8度破坏状态,9度破坏状态,10度破坏状态,11度破坏状态,12度破坏状态";
            ExcelReaderUtil.checkTitle(file.getInputStream(), 1, 0, title);
            ExcelResult excelResult = ExcelReaderUtil.readExcelBean(file.getInputStream(), CztMajorProjectsVo.class, 3, 0);
            List<CztMajorProjectsVo> list = excelResult.getData();
            if (PlatformObjectUtils.isEmpty(list)) {
                return RestResponse.fail("表格中无数据,请检查!");
            }
            for (CztMajorProjectsVo vo : list) {
                CztMajorProjectsEntity entity = new CztMajorProjectsEntity();
                BeanUtils.copyProperties(vo, entity);
                if (PlatformObjectUtils.isEmpty(entity.getDestructive6State())) {
                    entity.setDestructive6State("-");
                }
                if (PlatformObjectUtils.isEmpty(entity.getDestructive7State())) {
                    entity.setDestructive7State("-");
                }
                if (PlatformObjectUtils.isEmpty(entity.getDestructive8State())) {
                    entity.setDestructive8State("-");
                }
                if (PlatformObjectUtils.isEmpty(entity.getDestructive9State())) {
                    entity.setDestructive9State("-");
                }
                if (PlatformObjectUtils.isEmpty(entity.getDestructive10State())) {
                    entity.setDestructive10State("-");
                }
                if (PlatformObjectUtils.isEmpty(entity.getDestructive11State())) {
                    entity.setDestructive11State("-");
                }
                if (PlatformObjectUtils.isEmpty(entity.getDestructive12State())) {
                    entity.setDestructive12State("-");
                }
                entity.setCreateUser(PlatformSessionContext.getUserID());
                entity.setCreateUserName(sUser.getUserName());
                entity.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
                entity.setDelFlag(YNEnum.N.toString());
                entity.setId(UUIDGenerator.getUUID());
                String number = ("ZH" + "-" + generationNumberUtil.getFs(entity.getFortification()) + "-" + PinyinAPI.getPinYinHeadChar(entity.getProjectType()) + "-" +
                        getCode());
                entity.setCode(number);
                entity.setVersionId(versionId);
                domeFacilitiesRepository.save(entity);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return RestResponse.succeed("上传成功!");
    }

    private String updateVersionInfo(String id) {
        SmxVersionEntity entity = new SmxVersionEntity();
        entity.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        entity.setUpdateUser(PlatformSessionContext.getUserID());
        entity.setId(id);
        entity.setVersionStatus(1);
        lifelineEngineeringRepository.updateSmxVersion(entity);
        return entity.getId();
    }

    private String saveVersionInfo(String province, String city, String county, Integer type, String fileName) {
        SmxVersionEntity entity = new SmxVersionEntity();
        entity.setId(UUIDGenerator.getUUID());
        entity.setVersionCode(versionCodeUtils.getVersionCode(type));
        entity.setProvince(province);
        entity.setCity(city);
        entity.setCounty(county);
        entity.setFileName(fileName);
        entity.setVersionStatus(1);
        entity.setCreateUser(PlatformSessionContext.getUserID());
        entity.setCreateUserName(getUserName().getUserName());
        entity.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        entity.setDelFlag("0");
        entity.setType(type);
        lifelineEngineeringRepository.saveSmxVersion(entity);
        return entity.getId();
    }

    /**
     * 获取用户名字
     *
     * @return
     */
    public SUser getUserName() {
        String user = userService.getSUser(PlatformSessionContext.getUserID());
        return CreateGson.createGson().fromJson(user, SUser.class);
    }

    public synchronized String getCode() {
        String versionCode = "";
        String code = domeFacilitiesRepository.getCode();
        if (PlatformObjectUtils.isNotEmpty(code)) {
            String[] split = code.split("-");
            versionCode = split[3];
            StringBuilder stringBuilder = new StringBuilder();
            String t = String.valueOf(Integer.parseInt(versionCode) + 1);
            for (int i = t.length(); i < 4; i++) {
                stringBuilder.append("0");
            }
            versionCode = stringBuilder.append(t).toString();
        } else {
            versionCode = "0001";
        }
        return versionCode;
    }

    @Override
    public HashMap<String, Object> getByRegionAndType(Integer type, String province, String city, String county, Integer page, Integer size) {
        return domeFacilitiesRepository.getByRegionAndType(type, province, city, county, page, size);
    }

    @Override
    public void updateByTypeAndId(HashMap<Integer, Object> map) {
        for (Map.Entry<Integer, Object> entry : map.entrySet()) {
            domeFacilitiesRepository.updateByTypeAndId(entry.getKey(), entry.getValue());
        }
    }

    @Override
    public void deleteByTypeAndId(Integer type, String id) {

    }
}
